using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using BanZuiCloudControlAgent.Utils.Common;
using BanZuiCloudControlAgent.Utils.Logging;

namespace BanZuiCloudControlAgent.Utils.Database
{
    /// <summary>
    /// 数据库连接工厂，负责创建和管理SQLite数据库连接
    /// </summary>
    public class DbConnectionFactory
    {
        private static readonly Logger _logger = LogManager.GetLogger(nameof(DbConnectionFactory));
        private static string _dbFilePath;
        private static string _connectionString;
        private static bool _initialized = false;
        private static readonly object _lockObj = new object();

        /// <summary>
        /// 创建数据库连接
        /// </summary>
        /// <returns>SQLite数据库连接</returns>
        public static IDbConnection CreateConnection()
        {
            EnsureInitialized();
            return new SQLiteConnection(_connectionString);
        }

        /// <summary>
        /// 确保数据库已初始化
        /// </summary>
        private static void EnsureInitialized()
        {
            if (_initialized)
                return;

            lock (_lockObj)
            {
                if (_initialized)
                    return;

                try
                {
                    // 从ConfigurationManager获取数据库文件路径
                    _dbFilePath = ConfigurationManager.GetDatabaseFilePath("BanZuiCloudControl.db");
                    _connectionString = $"Data Source={_dbFilePath};Version=3;";
                    
                    // 确保数据库目录存在
                    string dbDirectory = Path.GetDirectoryName(_dbFilePath);
                    if (!Directory.Exists(dbDirectory))
                    {
                        Directory.CreateDirectory(dbDirectory);
                    }
                    
                    InitializeDatabase();
                    _initialized = true;
                }
                catch (Exception ex)
                {
                    _logger.Error("初始化数据库连接工厂失败", ex);
                    throw;
                }
            }
        }

        /// <summary>
        /// 初始化数据库，如果不存在则创建
        /// </summary>
        private static void InitializeDatabase()
        {
            try
            {
                if (!File.Exists(_dbFilePath))
                {
                    _logger.Info($"数据库文件不存在，正在创建: {_dbFilePath}");
                    SQLiteConnection.CreateFile(_dbFilePath);
                }
                
                // 创建必要的表
                using (var connection = new SQLiteConnection(_connectionString))
                {
                    connection.Open();
                    
                    // 创建消息表
                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText = @"
                            CREATE TABLE IF NOT EXISTS MqttMessages (
                                Id INTEGER PRIMARY KEY AUTOINCREMENT,
                                MessageId TEXT NOT NULL UNIQUE,
                                MessageType TEXT NOT NULL,
                                Timestamp TEXT NOT NULL,
                                DeviceCode TEXT NOT NULL,
                                Payload TEXT,
                                ProcessedTime TEXT,
                                Status INTEGER DEFAULT 0, -- 0:处理中, 1:处理完成, 2:处理失败
                                FailCount INTEGER DEFAULT 0, -- 失败次数
                                LastProcessTime TEXT, -- 最后处理时间
                                CreateTime TEXT NOT NULL
                            );
                            
                            CREATE INDEX IF NOT EXISTS idx_MqttMessages_MessageId ON MqttMessages(MessageId);
                            CREATE INDEX IF NOT EXISTS idx_MqttMessages_MessageType ON MqttMessages(MessageType);
                            CREATE INDEX IF NOT EXISTS idx_MqttMessages_Status ON MqttMessages(Status);
                        ";
                        command.ExecuteNonQuery();
                    }
                }
                
                _logger.Info("数据库初始化完成");
            }
            catch (Exception ex)
            {
                _logger.Error("初始化数据库失败", ex);
                throw;
            }
        }
    }
} 